﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：CommonModule.cs
// 功能描述：TongTongMall.Common
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Common.AutoMapper;
using TongTongMall.Modules;

namespace TongTongMall.Common
{
    [DependsOn(typeof(KernelModule))]
    public class CommonModule : BaseModule
    {
        private static readonly object _syncObj = new object();
        private static bool _createdMappingsBefore;

        private readonly IModuleFinder _moduleFinder;

        public CommonModule(IModuleFinder moduleFinder)
        {
            _moduleFinder = moduleFinder;
        }

        public override void PostInitialize()
        {
            CreateMappings();
        }
        private void CreateMappings()
        {
            lock (_syncObj)
            {
                //保证Mapper映射过程中是不可重复的
                if (_createdMappingsBefore)
                {
                    return;
                }

                FindAndAutoMapTypes();

                _createdMappingsBefore = true;
            }
        }
        private void FindAndAutoMapTypes()
        {
            var types = _moduleFinder.Find(type =>
                type.IsDefined(typeof(AutoMapAttribute)) ||
                type.IsDefined(typeof(AutoMapFromAttribute)) ||
                type.IsDefined(typeof(AutoMapToAttribute)))?.ToArray();
            if (types != null)
            {
                foreach (var type in types)
                {
                    AutoMapperHelper.CreateMap(type);
                }
            }
        }
    }
}
